<template>
    <div>
        <div class="header-line">
            <div class="icon-box">
                <i :class="icon" class="iconfont" @click="collapse"></i>

            </div>
            <div class="header-title">
                <span>admin管理系统</span>
            </div>
            <div class="avatar-box">
                <el-avatar :size="50" :src="user.avatar"></el-avatar>
            </div>
            <el-button type="primary" class="dropdown-button">
                {{ formatRole(user.role) }}【
                {{ user.name }}】
            </el-button>

            <div class="drawer-box">
                <el-button class="el-icon-setting drawer-button" type="primary" @click="drawer = true"></el-button>
            </div>
        </div>
        <el-drawer :visible.sync="drawer" title="个人设置" direction="rtl" size="25%">
            <el-col :span="24">
                <el-card shadow="hover" class="box-card centered-card blue" :show-close="false">
                    <div>
                        <el-avatar size="large" :src="user.avatar" fit="cover"
                            style="width: 100px;height: 100px;"></el-avatar>
                    </div>
                    <el-button type="success" size="small" @click="modAvatar">更换头像</el-button>
                </el-card>
                <el-card shadow="hover" class="box-card centered-card blue" :show-close="false">
                    <div>
                        <el-button class="el-icon-edit-outline" type="success"
                            @click="nameDialog = true">修改昵称</el-button>
                    </div>
                </el-card>
                <el-card shadow="hover" class="box-card centered-card green" :show-close="false">
                    <div>
                        <el-button class="el-icon-lock" type="success" @click="pwdDialog = true">修改密码</el-button>
                    </div>
                </el-card>
                <el-card shadow="hover" class="box-card centered-card red" :show-close="false">
                    <div>
                        <el-button class="el-icon-switch-button" type="danger" @click="logout">退出登录</el-button>
                    </div>
                </el-card>
                <el-card shadow="hover" class="box-card centered-card red" :show-close="false">
                    <div>
                        <el-button class="el-icon-delete" type="danger" @click="delUser">注销账号</el-button>
                    </div>
                </el-card>

            </el-col>
        </el-drawer>
        <el-dialog title="修改昵称" :visible.sync="nameDialog" width="30%" center>
            <el-form ref="nameForm" :model="nameForm" :rules="nameRules" label-width="100px">
                <el-form-item label="昵称" prop="name">
                    <el-input v-model="user.name" disabled></el-input>
                </el-form-item>
                <el-form-item label="新昵称" prop="name">
                    <el-input v-model="nameForm.name"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="nameDialog = false">取 消</el-button>
                <el-button type="primary" @click="modName">开始修改</el-button>
            </span>
        </el-dialog>
        <el-dialog title="修改密码" :visible.sync="pwdDialog" width="30%" center>
            <el-form ref="pwdForm" :model="pwdForm" :rules="pwdRules" label-width="100px">
                <el-form-item label="原密码" prop="opassword">
                    <el-input v-model="pwdForm.opassword" type="password" placeholder="请输入用户原密码"
                        style="width: 200px;"></el-input>

                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input v-model="pwdForm.password" type="password" placeholder="请输入用户密码"
                        style="width: 200px;"></el-input>

                </el-form-item>
                <el-form-item label="确认密码" prop="rpassword">
                    <el-input v-model="pwdForm.rpassword" type="password" placeholder="请输入用户密码"
                        style="width: 200px;"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="pwdDialog = false">取 消</el-button>
                <el-button type="primary" @click="modPwd">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'Header',
    props: {
        icon: String
    },
    data() {
        var validatePassword = (rule, value, callback) => {
            if (value == "") {
                callback(new Error('请输入确认密码'));
            } else if (value !== this.pwdForm.password) {
                callback(new Error('两次输入的密码不一致!'));
            } else {
                callback();
            }
        };
        var validateOldPwd = (rule, value, callback) => {
            if (value == "") {
                callback(new Error('请输入旧密码'));
            } else if (value !== this.user.password) {
                callback(new Error('密码不正确!'));
            } else {
                callback();
            }
        };
        return {
            user: JSON.parse(localStorage.getItem('CurUser')),
            roleData: [],
            drawer: false,
            nameDialog: false,
            pwdDialog: false,
            nameForm: {
                name: ''
            },
            nameRules: {
                name: [
                    { required: true, message: '请输入用户昵称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ]
            },
            pwdForm: {
                oassword: '',
                password: '',
                rpassword: ''
            },
            pwdRules: {
                opassword: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16个字符', trigger: 'blur' },
                    { validator: validateOldPwd, trigger: 'blur' }

                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16个字符', trigger: 'blur' }
                ],
                rpassword: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16个字符', trigger: 'blur' },
                    { validator: validatePassword, trigger: 'blur' }
                ]
            }
        }
    },

    methods: {
        toSetting() {
            console.log('toSetting')
            this.$router.push('/Setting')
        },
        collapse() {
            this.$emit('doCollapse')
        },
        loadRole() {
            this.$axios.post('/role/listPage', {
                pageSize: 1000,
                pageNum: 1,
                param: {
                }
            }).then(res => {
               
                if (res.code == 200) {
                    this.roleData = res.data
                } else {
                    this.$message.error(res.msg)
                }
            })
        }
        ,
        formatRole(role) {
            let temp = this.roleData.find(item => item.id == role)
            return temp && temp.name;
        },
        logout() {
            this.$confirm('确定要退出登录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loginout()
            }).catch(() => {
                this.$message({
                    message: "已取消",
                    type: 'info'
                })
            })
        },
        delUser() {
            this.$confirm('确定要注销账号吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/user/delUser/' + this.user.id).then(res => {
                    console.log(res)
                   
                    if (res.code == 200) {
                        this.loginout()
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    message: "已取消",
                    type: 'info'
                })
            })
        },
        modAvatar() {
            const input = document.createElement('input')
            input.type = 'file'
            input.accept = 'image/*'
            input.onchange = async () => {
                const file = input.files[0]
                if (file) {
                    try {
                        let formData = new FormData();
                        formData.append("file", file);
                        formData.append("name", file.name);
                        this.$axios.post('/file/upload', formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(res => {
                           
                            console.log(res)
                            if (res.code == 200) {
                                this.user.avatar = res.data.url
                                this.modUserAvatar(res.data.url)
                                this.$message({
                                    message: "上传成功",
                                    type: "success"
                                })
                            } else {
                                this.$message({
                                    message: '上传失败',
                                    type: 'error'
                                })
                            }
                        })
                    } catch (error) {
                        this.$message({
                            message: '上传失败',
                            type: 'error'
                        })
                    }
                } else {
                    this.$message({
                        message: '请选择文件',
                        type: 'error'
                    })
                }
            }
            input.click()
        },
        modUserAvatar(avatar) {
            this.$axios.get('/user/modAvatar?id=' + this.user.id + "&avatar=" + avatar).then(res => {
               
                if (res.code == 200) {
                    this.$message({
                        message: "修改成功",
                        type: "success"
                    })
                    this.getUserById()
                } else {
                    this.$message({
                        message: '修改失败',
                        type: 'error'
                    })
                }
            })
        },
        getUserById() {
            this.$axios.get('/user/info/' + this.user.id).then(res => {
               
                this.user = res.data
                this.$store.commit('setUser', res.data)
            })
        },
        modName() {
            this.$refs.nameForm.validate(valid => {
                if (valid) {
                    this.$axios.get('/user/modName?id=' + this.user.id + "&name=" + this.nameForm.name).then(res => {
                       
                        if (res.code == 200) {

                            this.$message({
                                message: '修改成功',
                                type: 'success',
                                onClose: () => {
                                    this.getUserById()
                                    this.nameDialog = false
                                }
                            })
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                        }
                    })
                } else {
                    this.$message({
                        message: '请输入昵称',
                        type: 'error'
                    })
                }
            })
        },
        modPwd() {
            this.$refs.pwdForm.validate(valid => {
                if (valid) {
                    this.$axios.get('/user/modPwd?id=' + this.user.id + "&password=" + this.pwdForm.password).then(res => {
                       
                        if (res.code == 200) {

                            this.$message({
                                message: '修改成功',
                                type: 'success',
                                onClose: () => {
                                    this.pwdDialog = false
                                    this.loginout()
                                }
                            })
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                        }
                    })
                } else {
                    this.$message({
                        message: '请输入昵称',
                        type: 'error'
                    })
                }
            })
        },
        loginout() {
            this.$axios.get('/user/logout/' + this.user.id).then(res => {
                console.log(res)
               
                if (res.code == 200) {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                        onClose: () => {

                            this.$router.push('/Login')
                            this.$store.commit('resetState')
                        }
                    })
                } else {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                }
            })
        }
    }, mounted() {
        this.$EventBus.$on('update-user', this.getUserById())
        this.loadRole()
    },
}
</script>
<style>
.header-line {
    display: flex;
    line-height: 60px;

}

.header-title {
    flex: 1;
    text-align: center;
    font-size: 24px;
    font-weight: 700;
}

.icon-box {
    margin-top: 5px;
}

.iconfont {
    font-size: 24px;
    color: white;
    cursor: pointer;
}

.avatar-box {
    margin-top: 5px;
    margin-left: 50px;
}

.dropdown-button {
    line-height: 50px;
    margin-left: 15px;
    height: 60px;
    justify-content: center;
    align-items: center;
    display: flex;
}

.drawer-box {
    margin-top: 5px;
    margin-left: 5px;

}

.drawer-button {
    font-size: 24px;
}

.box-card {
    height: auto;
    min-height: 50px;
    text-align: center;
    border-radius: 25px;
    margin: 10px;
}

.card-row {
    display: flex;
    justify-content: center;
}

.centered-card {
    display: flex;
    justify-content: center;
    align-items: center;
}

.red {
    background-color: rgb(231, 9, 9);
}

.green {
    background-color: rgb(152, 246, 11);
}

.purple {
    background-color: rgb(135, 53, 212);
}

.blue {
    background-color: rgb(10, 138, 207);
}

.orange {
    background-color: chocolate;
}

.grey {
    background-color: grey;
}

.pink {
    background-color: blanchedalmond;
}

.gold {
    background-color: goldenrod;
}
</style>